<template>
  <div>
    <el-container class="header">
      <!-- 头 -->
      <el-header class="father">
        <el-row :gutter="20">
          <el-col :span="19">
            <el-form
              :inline="true"
              :model="formInline"
              class="demo-form-inline"
            >
              <el-form-item label="关键字">
                <el-input
                  v-model="formInline.keyword"
                  placeholder="根据文章标题搜索"
                ></el-input>
              </el-form-item>
              <el-form-item label="状态">
                <el-select
                  v-model="formInline.state"
                  placeholder="请选择"
                  style="width: 280px"
                >
                  <el-option label="启用" :value="1"></el-option>
                  <el-option label="停用" :value="0"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button class="confirm">清空</el-button>
                <el-button type="primary" class="cancel" @click="onSubmit"
                  >搜索</el-button
                >
              </el-form-item>
            </el-form>
          </el-col>
          <el-col :span="5">
            <!-- 新增用户表单 -->
            <el-button
              class="added"
              type="success"
              icon="el-icon-edit"
              @click="openDrawer('add')"
              >新增技巧</el-button
            >
          </el-col>
        </el-row>

        <!-- 预览 -->
        <el-dialog title="预览文章" :visible.sync="previewArticle" width="50%">
          <h2>{{ previewItem.title }}</h2>
          <div>
            <span> {{ createTime }} </span
            ><span> {{ previewItem.username }} </span
            ><i class="el-icon-view"> </i><span> {{ previewItem.visits }}</span>
          </div>
          <div class="content" v-html="previewItem.articleBody"></div>
        </el-dialog>

        <!-- 新增&编辑 -->
        <el-dialog
          :title="drawerTitle"
          :visible.sync="dialogFormVisible"
          width="50%"
        >
          <el-form :model="form" :rules="rules" ref="form">
            <el-form-item label="文章标题" label-width="120px" prop="title">
              <el-input
                v-model="form.title"
                placeholder="请输入文章标题"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="文章内容"
              label-width="120px"
              prop="articleBody"
            >
              <quill-editor
                v-model="form.articleBody"
                @blur="$refs.form.validateField('articleBody')"
              ></quill-editor>
            </el-form-item>
            <el-form-item label="视频地址" label-width="120px">
              <el-input
                v-model="form.videoURL"
                placeholder="请输入视频地址"
              ></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" style="margin-right: 190px">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="submit">确 定</el-button>
          </div>
        </el-dialog>
      </el-header>

      <!-- 身体 -->
      <el-main>
        <!-- 数据条数 -->
        <div class="recording">
          <span
            ><i class="el-icon-info"> </i>数据一共
            {{ tableData.counts }} 条</span
          >
        </div>
        <!-- table表格数据区域 -->
        <el-table :data="list" style="width: 100%" stripe v-loading="loading">
          <el-table-column type="index" label="序号" align="center">
          </el-table-column>
          <el-table-column prop="title" label="文章标题" align="center">
          </el-table-column>
          <el-table-column prop="visits" label="阅读数" align="center">
          </el-table-column>
          <el-table-column prop="username" label="录入人" align="center">
          </el-table-column>
          <el-table-column label="录入时间" align="center" width="180">
            <template v-slot="{ row }">
              <span>
                {{
                  row.createTime.substring(0, 10) +
                  " " +
                  row.createTime.substring(11, 19)
                }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center">
            <template v-slot="{ row }">
              <span>
                {{
                  row.state === 1 ? "已启用" : row.state === 0 ? "已禁用" : "无"
                }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="300" align="center">
            <!-- 表格子项的作用域插槽 -->
            <template #default="{ row }">
              <div v-if="row.isEdit">
                <el-button type="text" @click="preview(row.id)">预览</el-button>
                <el-button type="text" @click="handoff(row, row.id)"
                  >禁用</el-button
                >
                <el-button type="text" @click="openDrawer('edit', row.id)"
                  >修改</el-button
                >
                <el-button type="text" @click="del(row.id)">删除</el-button>
              </div>
              <div v-else>
                <el-button type="text" @click="preview(row.id)">预览</el-button>
                <el-button type="text" @click="handoff(row, row.id)"
                  >启用</el-button
                >
                <el-button type="text" disabled>修改</el-button>
                <el-button type="text" disabled>删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页组件区域 -->
        <el-row type="flex" style="height: 60px" align="middle" justify="end">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryObj.page"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="queryObj.pagesize"
            layout="prev, pager, next, sizes, jumper"
            :total="tableData.counts"
          >
          </el-pagination>
        </el-row>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'

import {
  list,
  add,
  update,
  detail,
  remove,
  changeState
} from '@/api/hmmm/articles.js'

export default {
  components: {
    quillEditor
  },
  data () {
    return {
      loading: false,
      dialogFormVisible: false,
      previewArticle: false,
      drawerType: 'add',
      form: {
        id: null,
        title: '',
        articleBody: '',
        videoURL: ''
      },
      formInline: {
        keyword: null,
        state: null
      },
      id: 0,
      queryObj: {
        page: 1, // 控制当前页
        pagesize: 10, // 控制每页有几条数据
        keyword: null,
        state: null
      },
      // 验证规则
      rules: {
        title: [{ required: true, message: '请输入文章标题', trigger: 'blur' }],
        articleBody: [
          { required: true, message: '请输入文章内容', trigger: 'blur' }
        ]
      },
      tableData: {},
      list: [],
      previewItem: {},
      createTime: null
    }
  },
  created () {
    this.initTable()
  },
  methods: {
    // 获取table数据
    async initTable () {
      this.loading = true
      const { data } = await list(this.queryObj)
      this.tableData = data
      this.list = data.items
      this.list.forEach((item) => {
        this.$set(item, 'isEdit', item.state)
      })
      this.loading = false
    },

    // 提交表单
    async submit () {
      try {
        await this.$refs.form.validate()
        if (this.drawerType === 'add') {
          // 发起添加请求
          console.log(this.form)
          await add(this.form)
        }
        if (this.drawerType === 'edit') {
          // 发起修改请求
          await update(this.form)
        }
        this.form = {
          id: null,
          title: '',
          articleBody: '',
          videoURL: ''
        }
        // 关闭表单框
        this.dialogFormVisible = false

        // 提示用户
        this.$message.success(
          this.drawerType === 'add' ? '添加成功' : '修改成功'
        )

        // 重新获取新的数据渲染页面
        this.initTable()
      } catch (error) {
        this.$message.error('请输入必填项')
      }
    },

    // 打开编辑功能
    async openDrawer (type, id) {
      this.drawerType = type
      this.dialogFormVisible = true
      if (type === 'edit') {
        this.id = id
        const { data } = await detail({ id })
        this.form.title = data.title
        this.form.articleBody = data.articleBody
        this.form.videoURL = data.videoURL
        this.form.id = this.id
      }
    },
    // 预览
    async preview (id) {
      this.previewArticle = true
      if (this.list) {
        const data = this.list.find((item) => item.id === id)
        this.previewItem = data
        this.createTime =
          this.previewItem.createTime.substring(0, 10) +
          ' ' +
          this.previewItem.createTime.substring(11, 19)
      }
    },
    // 删除功能
    async del (id) {
      try {
        await remove({ id })
        this.$message.success('删除成功')
        this.initTable()
      } catch (error) {
        this.$message.error('删除失败')
      }
    },
    // 查询
    onSubmit () {
      this.queryObj.keyword = this.formInline.keyword
      this.queryObj.state = this.formInline.state
      this.initTable()
      this.formInline.keyword = null
      this.formInline.state = null
    },
    // 分页功能
    // pagesize改变时会触发
    handleSizeChange (val) {
      this.queryObj.pagesize = val
      this.queryObj.page = 1
      this.initTable()
    },
    // page当前页改变时会触发
    async handleCurrentChange (val) {
      // 改变参数对象中的当前页
      this.queryObj.page = val
      this.initTable()
    },
    // 切换
    async handoff (row, id) {
      row.isEdit = !row.isEdit
      const state = +row.isEdit
      await changeState({ id: id, state: state })
      this.initTable()
      this.$message.success('操作成功')
    }
  },
  computed: {
    drawerTitle () {
      if (this.drawerType === 'add') return '新增文章'
      if (this.drawerType === 'edit') return '修改文章'
      else {
        return 'add'
      }
    }
  }
}
</script>

<style scoped lang="less">
.header {
  background-color: #fff;
  margin: 10px 20px;
  border-radius: 5px;
  box-shadow: 0px 0px 20px #ccc;
  .father {
    padding: 20px 20px;
    height: 100px;
    .added {
      height: 36px;
      width: 96px;
      font-size: 12px;
      padding-left: 11px;
      margin-left: 140px;
    }
  }
}
.recording {
  height: 35px;
  width: 100%;
  padding: 8px 16px;
  background-color: #f4f4f5;
  border-radius: 5px;
  span {
    font-size: 13px;
    color: #909399;
  }
}
.confirm {
  height: 36px;
  width: 56px;
  padding-left: 15px;
  font-size: 12px;
}
.cancel {
  height: 36px;
  width: 56px;
  padding-left: 15px;
  font-size: 12px;
}
.content {
  width: 100%;
  min-height: 65px;
  margin-top: 10px;
  padding: 25px 15px;
  border-top: 1px dashed;
  background-color: #f5f5f5;
}
</style>
